package com.danhuang.cloud.danhuangdaily.service.Impl;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.danhuang.cloud.danhuangcore.constant.OpenIdConstant;
import com.danhuang.cloud.danhuangcore.constant.ResConstant;
import com.danhuang.cloud.danhuangcore.entity.AlbumDTO;
import com.danhuang.cloud.danhuangcore.model.DhAlbumInfo;
import com.danhuang.cloud.danhuangcore.model.DhPhoneInfo;
import com.danhuang.cloud.danhuangcore.model.DhRes;
import com.danhuang.cloud.danhuangcore.service.FileDubboService;
import com.danhuang.cloud.danhuangcore.utils.CreateIdUtil;
import com.danhuang.cloud.danhuangdaily.constant.DailyConstant;
import com.danhuang.cloud.danhuangdaily.mapper.DhAlbumInfoMapper;
import com.danhuang.cloud.danhuangdaily.mapper.DhPhoneInfoMapper;
import com.danhuang.cloud.danhuangdaily.service.PhotoService;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author huangwubin
 */
@Service
@Slf4j
public class PhotoServiceImpl implements PhotoService {

    @Resource
    private DhAlbumInfoMapper dhAlbumInfoMapper;

    @DubboReference
    private FileDubboService fileDubboService;

    @Resource
    private DhPhoneInfoMapper dhPhoneInfoMapper;

    @Override
    public DhRes albumList(HttpServletRequest request) {
        try{
            String openId = request.getHeader("openId");

            LambdaQueryWrapper<DhAlbumInfo> lq = Wrappers.lambdaQuery();
            lq.eq(DhAlbumInfo::getPermission, "public");
            if(OpenIdConstant.check(openId)){
                lq.clear();
            }

            lq.eq(DhAlbumInfo::getDetFlg,0);

            Map<String, Object> result = new HashMap<>();
            result.put("check", OpenIdConstant.check(openId));
            result.put("data", dhAlbumInfoMapper.selectList(lq));

            return DhRes.success(result);
        }catch (Exception e){
            log.error("相册列表异常",e);
            return DhRes.fail(ResConstant.SYSTEM_ERROR_CODE);
        }
    }

    @Override
    public DhRes albumDetail(HttpServletRequest request, Page page, String albumId) {

        try{
            String openId = request.getHeader("openId");

            DhAlbumInfo dhAlbumInfo = dhAlbumInfoMapper.selectOne(Wrappers.<DhAlbumInfo>lambdaQuery()
                    .eq(DhAlbumInfo::getId, albumId)
                    .eq(DhAlbumInfo::getDetFlg,0));
            if(!OpenIdConstant.check(openId)){
                if ("private".equals(dhAlbumInfo.getPermission())){
                    return DhRes.success();
                }
            }

            IPage<DhPhoneInfo> photos = dhPhoneInfoMapper.selectPage(page,
                    new LambdaQueryWrapper<DhPhoneInfo>().eq(DhPhoneInfo::getAlbumId, albumId)
                            .eq(DhPhoneInfo::getDetFlg, 0).orderByDesc(DhPhoneInfo::getCreateTime));


            return DhRes.success(photos);
        }catch (Exception e){
            log.error("相册列表异常",e);
            return DhRes.fail(ResConstant.SYSTEM_ERROR_CODE);
        }
    }

    @Override
    public DhRes albumCreate(AlbumDTO albumDTO) {
        try {

            int n = dhAlbumInfoMapper.selectCount(new LambdaQueryWrapper<DhAlbumInfo>()
                    .eq(DhAlbumInfo::getAlbum,albumDTO.getAlbum())
                    .eq(DhAlbumInfo::getDetFlg,0));

            if(n > 0){
                return DhRes.fail(ResConstant.DUPLICATE_CODE,
                        StrUtil.format(ResConstant.map.get(ResConstant.DUPLICATE_CODE), "相册名"));
            }

            DhAlbumInfo dhAlbumInfo = new DhAlbumInfo();
            dhAlbumInfo.setAlbum(albumDTO.getAlbum());
            dhAlbumInfo.setCreateDate(new Date());
            dhAlbumInfo.setPermission(albumDTO.getPermission());

            dhAlbumInfoMapper.insert(dhAlbumInfo);

            return DhRes.success(dhAlbumInfo.getId());
        }catch (Exception e){
            log.error("创建相册异常",e);
            return DhRes.fail(ResConstant.SYSTEM_ERROR_CODE);
        }
    }

    @Override
    public DhRes photoUpload(String albumId, String path, MultipartFile file, String cover) {

        try{
            int n = dhAlbumInfoMapper.selectCount(new LambdaQueryWrapper<DhAlbumInfo>()
                    .eq(DhAlbumInfo::getId,albumId));

            if(n == 0){
                return DhRes.fail(ResConstant.NO_RESULT_CODE);
            }

            String mainPath = path  + StrUtil.SLASH + file.getOriginalFilename();

            DhRes dhRes = fileDubboService.uploader(mainPath, IoUtil.readBytes(file.getInputStream()));
            if(!dhRes.isSuccess()){
                return dhRes;
            }

            String id = CreateIdUtil.createId("P");

            File tempFile = File.createTempFile(id , ".jpg");

            Thumbnails.of(file.getInputStream()).scale(0.5).toOutputStream(new FileOutputStream(tempFile));

            String copyPath = path  + StrUtil.SLASH + tempFile.getName();

            DhRes dhResS = fileDubboService.uploader(copyPath, IoUtil.readBytes(new FileInputStream(tempFile)));
            tempFile.delete();
            if(!dhResS.isSuccess()){
                return dhResS;
            }

            dhPhoneInfoMapper.insert(
                    DhPhoneInfo.builder()
                            .photoId(id)
                            .photoName(file.getOriginalFilename())
                            .albumId(Integer.valueOf(albumId))
                            .createTime(new Date())
                            .imgUrl(copyPath)
                            .bigImgUrl(mainPath)
                            .build());

            if(StrUtil.isNotBlank(cover)){
                DhAlbumInfo dhAlbumInfo = new DhAlbumInfo();
                dhAlbumInfo.setId(Integer.valueOf(albumId));
                dhAlbumInfo.setCoverUrl(copyPath);
                dhAlbumInfoMapper.updateById(dhAlbumInfo);
            }

            return DhRes.success();
        }catch (Exception e){
            log.error("图片上传异常",e);
            return DhRes.fail(ResConstant.SYSTEM_ERROR_CODE);
        }
    }

    @Override
    public DhRes test(String albumId, String path) {

        return fileDubboService.test(albumId,path);
    }

    @Override
    public byte[] photoDown(String path) {
        return fileDubboService.down(path);
    }

    @Override
    public DhRes photoBig(String photoId) {
//        dhPhoneInfoMapper.

        return null;
    }
}
